<template>
  <view class="h5-container">
    <web-view 
      :src="h5PageUrl" 
      class="webview" 
      @message="handleMessage"
    />
  </view>
</template>

<script setup lang="ts">
import Taro from '@tarojs/taro'
import { onMounted, ref } from 'vue'

const h5PageUrl = ref('')

// Handle messages from H5 page
const handleMessage = (event: any) => {
  console.log('Received message from H5 page:', event)
  
  // Extract the message data
  const messageData = event.detail.data
  
  // Process the message
  if (messageData && messageData.length > 0) {
    const data = messageData[0]
    
    if (data.type === 'user_message') {
      // Show a toast with the received message
      Taro.showToast({
        title: `Received: ${data.message}`,
        icon: 'none',
        duration: 3000
      })
      
      console.log('Message from H5:', data.message)
    } 
    else if (data.type === 'file_upload') {
      // Handle file upload from H5
      handleFileUpload(data)
    }
  }
}

// Handle file upload from H5 page
const handleFileUpload = (fileData: any) => {
  Taro.showToast({
    title: 'Received file from H5',
    icon: 'loading',
    duration: 2000
  })
  
  console.log('File data from H5:', fileData)
  
  // Convert base64 to blob for upload
  const base64Data = fileData.fileData.split(',')[1]
  const byteString = atob(base64Data)
  const mimeString = fileData.fileData.split(',')[0].split(':')[1].split(';')[0]
  const ab = new ArrayBuffer(byteString.length)
  const ia = new Uint8Array(ab)
  
  for (let i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i)
  }
  
  const blob = new Blob([ab], { type: mimeString })
  const fileName = fileData.fileName || 'upload_' + Date.now() + '.jpg'
  
  // Create a temporary file path (this is a workaround for Taro)
  const tempFilePath = URL.createObjectURL(blob)
  
  // Upload the file using Taro's upload API
  Taro.uploadFile({
    url: 'https://anfine.huasun-healthcare.com:80/file-service/FileUpload/custom_saveImage',
    filePath: tempFilePath,
    name: 'file',
    fileName: fileName,
    header: {
      'content-type': 'multipart/form-data'
    },
    success: (uploadRes) => {
      console.log('Upload success:', uploadRes)
      Taro.showToast({
        title: 'File uploaded successfully',
        icon: 'success',
        duration: 2000
      })
      
      // Send success message back to H5
      // Note: This requires implementing a postMessage listener in the H5 page
    },
    fail: (err) => {
      console.error('Upload failed:', err)
      Taro.showToast({
        title: 'File upload failed',
        icon: 'error',
        duration: 2000
      })
    }
  })
}

onMounted(() => {
  // Set the URL to our H5 page
  // In a real project, this would be your deployed H5 page URL
  // For local development, you might need to adjust this path
  h5PageUrl.value = `${window.location.origin}/design/h5/index.html`
  
  // If you have specific page parameters, you can use them
  const params = Taro.getCurrentInstance().router?.params
  if (params) {
    // Build query string from parameters
    const queryParams = Object.keys(params)
      .map(key => `${key}=${encodeURIComponent(params[key])}`)
      .join('&')
    
    if (queryParams) {
      h5PageUrl.value += `?${queryParams}`
    }
  }
  
  console.log('Loading H5 page:', h5PageUrl.value)
})
</script>

<style scoped>
.h5-container {
  width: 100%;
  height: 100vh;
}

.webview {
  width: 100%;
  height: 100%;
}
</style>